import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controller/auth_controller.dart';
import '../controller/home_controller.dart';

class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {
  final bool showBalance;
  final VoidCallback? onAvatarTap;

  const CustomAppBar({
    Key? key,
    this.showBalance = true,
    this.onAvatarTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 0),
      decoration: const BoxDecoration(
        color: Colors.transparent,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Flexible(
            flex: 1,
            child: _buildLeftSection(),
          ),
          Flexible(
            flex: 1,
            child: _buildRightSection(),
          ),
        ],
      ),
    );
  }

  Widget _buildLeftSection() {
    return Obx(() {
      final authController = Get.find<AuthController>();
      final isLoggedIn = authController.isLoggedIn.value;

      if (isLoggedIn) {
        return _buildUserInfo(authController);
      } else {
        return _buildAppInfo();
      }
    });
  }

  Widget _buildUserInfo(AuthController authController) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        // ☰ 图标
        GestureDetector(
          onTap: onAvatarTap,
          child: Container(
            padding: const EdgeInsets.all(8),
            child: CircleAvatar(
              radius: 14,
              backgroundImage: const AssetImage('assets/app_logo.png'),
              backgroundColor: Colors.transparent,
            ),
          ),
        ),
        const SizedBox(width: 8),
        // 用户信息（移除头像logo）
        GestureDetector(
          onTap: onAvatarTap,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
                Text(
                   'BitPlanera',
                   style: const TextStyle(
                     color: Colors.white,
                     fontSize: 16,
                     fontWeight: FontWeight.bold,
                   ),
                   overflow: TextOverflow.visible,
                   maxLines: 1,
                 ),
                Text(
                  'ID: ${authController.userId.isNotEmpty ? authController.userId : '--'}',
                  style: TextStyle(
                    color: Colors.grey[400],
                    fontSize: 12,
                  ),
                  overflow: TextOverflow.visible,
                  maxLines: 1,
                ),
              ],
            ),
          )]);
        
    
  }

  Widget _buildAppInfo() {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        // ☰ 图标
        Container(
          padding: const EdgeInsets.all(8),
          child: const Text(
            '☰',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
        const SizedBox(width: 8),
        // 圆形应用图标
        Container(
          padding: const EdgeInsets.all(8),
          child: CircleAvatar(
            radius: 14,
            backgroundImage: const AssetImage('assets/app_logo.png'),
            backgroundColor: Colors.transparent,
          ),
        ),
        const SizedBox(width: 8),
        // 应用名称（移除logo图标）
        const Flexible(
          child: Text(
            'BitPlanera',
            style: TextStyle(
              color: Colors.white,
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
            overflow: TextOverflow.visible,
            maxLines: 1,
          ),
        ),
      ],
    );
  }

  Widget _buildRightSection() {
    return Obx(() {
      final authController = Get.find<AuthController>();
      final isLoggedIn = authController.isLoggedIn.value;

      if (isLoggedIn && showBalance) {
        return _buildBalanceInfo();
      } else {
        return _buildBtcPrice();
      }
    });
  }

  Widget _buildBalanceInfo() {
    return Obx(() {
      final homeController = Get.find<HomeController>();
      final btcBalance = homeController.btcBalance;
      final btcPrice = homeController.btcPrice;
      final usdValue = homeController.getFormattedUsdValue();

      return GestureDetector(
        onTap: onAvatarTap,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          mainAxisSize: MainAxisSize.min,
          children: [
            // BTC余额 - 使用递增动画
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Image(
                  image: AssetImage("assets/bit_bitcoin_logo.png"),
                  width: 18,
                  height: 18,
                ),
                const SizedBox(width: 4),
                Flexible(
                  child: PreciseAnimatedCounterText(
                    value: btcBalance,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                    ),
                    suffix: 'BTC',
                  ),
                ),
              ],
            ),
            const SizedBox(height: 2),
            // BTC当前价格 - 使用平滑滑入和淡入效果
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                // Icon(
                //   Icons.currency_bitcoin,
                //   color: Color(0xFFF7931A),
                //   size: 12,
                // ),
                // SizedBox(width: 3),
                Flexible(
                  child: AnimatedSwitcher(
                    duration: Duration(milliseconds: 500),
                    transitionBuilder:
                        (Widget child, Animation<double> animation) {
                      return SlideTransition(
                        position: Tween<Offset>(
                          begin: Offset(0.0, 0.5),
                          end: Offset.zero,
                        ).animate(CurvedAnimation(
                          parent: animation,
                          curve: Curves.easeOutCubic,
                        )),
                        child: FadeTransition(
                          opacity: animation,
                          child: child,
                        ),
                      );
                    },
                    child: Text(
                      '\1BTC = \$$btcPrice',
                      key: ValueKey(btcPrice),
                      style: TextStyle(
                        color: Colors.green[400],
                        fontSize: 10,
                        fontWeight: FontWeight.w600,
                      ),
                      overflow: TextOverflow.clip,
                      maxLines: 1,
                    ),
                  ),
                ),
                SizedBox(width: 3),
                Container(
                  width: 4,
                  height: 4,
                  decoration: BoxDecoration(
                    color: Colors.green[400],
                    shape: BoxShape.circle,
                  ),
                ),
              ],
            )
          ],
        ),
      );
    });
  }

  Widget _buildBtcPrice() {
    return Obx(() {
      final homeController = Get.find<HomeController>();
      final btcPrice = homeController.btcPrice;

      return Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            Icons.currency_bitcoin,
            color: Color(0xFFF7931A),
            size: 12,
          ),
          SizedBox(width: 3),
          Flexible(
            child: AnimatedSwitcher(
              duration: Duration(milliseconds: 500),
              transitionBuilder: (Widget child, Animation<double> animation) {
                return SlideTransition(
                  position: Tween<Offset>(
                    begin: Offset(0.0, 0.5),
                    end: Offset.zero,
                  ).animate(CurvedAnimation(
                    parent: animation,
                    curve: Curves.easeOutCubic,
                  )),
                  child: FadeTransition(
                    opacity: animation,
                    child: child,
                  ),
                );
              },
              child: Text(
                '\$ $btcPrice',
                key: ValueKey(btcPrice),
                style: TextStyle(
                  color: Colors.green[400],
                  fontSize: 10,
                  fontWeight: FontWeight.w600,
                ),
                overflow: TextOverflow.visible,
                maxLines: 1,
              ),
            ),
          ),
          SizedBox(width: 3),
          Container(
            width: 4,
            height: 4,
            decoration: BoxDecoration(
              color: Colors.green[400],
              shape: BoxShape.circle,
            ),
          ),
        ],
      );
    });
  }

  @override
  Size get preferredSize => const Size.fromHeight(70);
}

// 精确动画组件
class PreciseAnimatedCounterText extends StatelessWidget {
  final String value;
  final TextStyle style;
  final String suffix;

  const PreciseAnimatedCounterText({
    Key? key,
    required this.value,
    required this.style,
    this.suffix = '',
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final numericValue = double.tryParse(value) ?? 0.0;

    return TweenAnimationBuilder<double>(
      tween: Tween<double>(begin: 0, end: numericValue),
      duration: Duration(milliseconds: 1000),
      curve: Curves.easeOutCubic,
      builder: (context, animatedValue, child) {
        // 当动画接近完成时（99%以上），显示原始精确字符串
        if (animatedValue / numericValue > 0.99) {
          return Text(
            '$value $suffix',
            style: style,
            overflow: TextOverflow.visible,
            maxLines: 1,
          );
        } else {
          // 动画过程中使用数值动画，但保持足够的精度
          String formattedValue;
          if (animatedValue < 0.000001) {
            // 对于非常小的数值，使用科学计数法或更高精度
            formattedValue = animatedValue.toStringAsExponential(6);
          } else {
            // 动态调整小数位数以保持精度
            int decimals = _calculateOptimalDecimals(animatedValue);
            formattedValue = animatedValue.toStringAsFixed(decimals);
          }

          return Text(
            '$formattedValue $suffix',
            style: style,
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
          );
        }
      },
    );
  }

  // 根据数值大小动态计算最佳小数位数
  int _calculateOptimalDecimals(double value) {
    if (value == 0) return 1;

    // 计算需要多少位小数才能显示有意义的数字
    int decimals = 0;
    double temp = value;

    while (temp < 1 && decimals < 15) {
      temp *= 10;
      decimals++;
    }

    // 至少保留8位小数，最多15位
    return decimals < 8 ? 8 : (decimals > 15 ? 15 : decimals + 2);
  }
}
